import Vue from "vue";
import Router from "vue-router";
import { getToken } from "@/utils/auth";
import { MessageBox } from "element-ui";
import store from "../store/index";
import { getUserInfo, getConfig } from "@/api/user";

Vue.use(Router);

/* Layout */
import Layout from "@/layout/index.vue";

/**
 * Note: 路由配置项
 *
 * hidden: true                     // 当设置 true 的时候该路由不会再侧边栏出现 如401，login等页面，或者如一些编辑页面/edit/1
 * alwaysShow: true                 // 当你一个路由下面的 children 声明的路由大于1个时，自动会变成嵌套的模式--如组件页面
 *                                  // 只有一个时，会将那个子路由当做根路由显示在侧边栏--如引导页面
 *                                  // 若你想不管路由下面的 children 声明的个数都显示你的根路由
 *                                  // 你可以设置 alwaysShow: true，这样它就会忽略之前定义的规则，一直显示根路由
 * redirect: noRedirect             // 当设置 noRedirect 的时候该路由在面包屑导航中不可被点击
 * name:'router-name'               // 设定路由的名字，一定要填写不然使用<keep-alive>时会出现各种问题
 * query: '{"id": 1, "name": "ry"}' // 访问路由的默认传递参数
 * roles: ['admin', 'common']       // 访问路由的角色权限
 * permissions: ['a:a:a', 'b:b:b']  // 访问路由的菜单权限
 * meta : {
    noCache: true                   // 如果设置为true，则不会被 <keep-alive> 缓存(默认 false)
    title: 'title'                  // 设置该路由在侧边栏和面包屑中展示的名字
    icon: 'svg-name'                // 设置该路由的图标，对应路径src/assets/icons/svg
    breadcrumb: false               // 如果设置为false，则不会在breadcrumb面包屑中显示
    activeMenu: '/system/user'      // 当路由设置了该属性，则会高亮相对应的侧边栏。
  }
 */

// 公共路由
export const constantRoutes = [
  {
    path: "/",
    redirect: "login",
  },
  {
    path: "/login",
    component: () => import("@/views/login"),
    hidden: true,
  },
  {
    path: "/forgetPassword",
    component: () => import("@/views/forgetPassword"),
    hidden: true,
  },
  {
    path: "/register",
    component: () => import("@/views/register"),
    hidden: true,
  },
  {
    path: "/404",
    component: () => import("@/views/error/404"),
    hidden: true,
  },
  {
    path: "/401",
    component: () => import("@/views/error/401"),
    hidden: true,
  },
  {
    path: "/",
    component: Layout,
    children: [
      {
        path: '/index',
        name: "index",
        component: () => import("@/views/index"),
        meta: { title: "首页" },
      },
      {
        path: "/user/testee",
        name: "testee",
        component: () => import("@/views/user/testee"),
        meta: { title: "被测人员" },
      },
      {
        path: "/user/other",
        name: "other",
        component: () => import("@/views/user/other"),
        meta: { title: "其他人员" },
      },
      {
        path: "/user/role",
        name: "role",
        component: () => import("@/views/user/role"),
        meta: { title: "角色管理" },
      },
      {
        path: "/data/analysis",
        name: "analysis",
        component: () => import("@/views/data/analysis"),
        meta: { title: "分析评价" },
      },
      {
        path: '/data/analysis/record',
        name: 'record',
        component: () => import("@/views/data/analysis/record"),
        meta: { title: "评价记录" },
      },
      {
        path: "/data/visual",
        name: "visual",
        component: () => import("@/views/data/visual"),
        meta: { title: "数据可视化" },
      },
      {
        path: "/teaching",
        name: "teaching",
        component: () => import("@/views/teaching"),
        meta: { title: "示教管理" },
      },
      {
        path: "/teaching/detail",
        name: 'detail',
        component: () => import("@/views/teaching/detail"),
        meta: { title: "示教详情" },
      },
      {
        path: "/device/device",
        name: "device",
        component: () => import("@/views/device/device"),
        meta: { title: "设备管理" },
      },
      {
        path: "/device/parameter",
        name: "parameter",
        component: () => import("@/views/device/parameter"),
        meta: { title: "参数设置" },
      },
      {
        path: "/system/logs",
        name: "logs",
        component: () => import("@/views/system/logs"),
        meta: { title: "系统日志" },
      },
      {
        path: "/about",
        name: "about",
        component: () => import("@/views/about"),
        meta: { title: "关于" },
      },
      {
        path: "/personal",
        name: "personal",
        component: () => import("@/views/user/personal"),
        meta: { title: "个人中心" },
      },
      {
        path: "/test/user",
        name: "user",
        component: () => import("@/views/test/user"),
        meta: { title: "操作测评一" },
      },
      {
        path: "/test/planeGame",
        name: "planeGame",
        component: () => import("@/views/test/planeGame"),
        meta: { title: "操作测评二" },
      },
      {
        path: '/test/recording',
        name: 'recording',
        component: () => import("@/views/test/recording"),
        meta: { title: "操作测评三" },
      },
      {
        path: "/test/video",
        name: "video",
        component: () => import("@/views/test/video"),
        meta: { title: "视频播放" },
      },
      {
        path: '/test/management',
        name: 'management',
        component: () => import("@/views/test/management"),
        meta: { title: "数据管理" },
      },
      {
        path: '/test/report',
        name: 'report',
        component: () => import("@/views/test/report"),
        meta: { title: "测评报告" },
      }
    ],
  },
];

// 防止连续点击多次路由报错
let routerPush = Router.prototype.push;
let routerReplace = Router.prototype.replace;
// push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((err) => err);
};
// replace
Router.prototype.replace = function push(location) {
  return routerReplace.call(this, location).catch((err) => err);
};

const router = new Router({
  mode: "history", // 去掉url中的#
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes,
});

const whiteList = ["/login", "/register", "/forgetPassword"];

router.beforeEach((to, from, next) => {
  if (getToken()) {
    getUserInfo().then((res) => {
      store.commit("SET_USER_INFO", res.data);
      if (res.data.enterAssess === 0) {
        store.commit('SET_TEST', false)
        getConfig().then(config => {
          localStorage.setItem('wsUrl', config.data.websocketAddress)
          store.commit('SET_CONFIG', config.data)
          localStorage.setItem('gameMode', config.data.gameMode)
          localStorage.setItem('setDifficulty', config.data.gameDifficulty)
        })
        if (localStorage.getItem('testUserId') == null || localStorage.getItem('testTaskId') == null) {
          store.state.user.user = true
        }
        next()
      } else {
        store.commit('SET_TEST', true)
        store.dispatch("GenerateRoutes").then((routes) => {
          if (routes.includes(to.path)) {
            next();
          } else {
            next("/404");
          }
        });
      }
    });
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      MessageBox.alert("未登录，请重新登录！", "系统提示", { type: "error" });
      next("/login");
    }
  }
});

export default router;
